import * as echarts from "echarts";
import { onMounted, onUnmounted, type Ref } from "vue";

export function useEchartsResize(chartInstance: Ref<echarts.ECharts | null>, chartDom: Ref<HTMLElement | null>, options: echarts.EChartsOption) {
  // 初始化图表
  const initChart = () => {
    if (chartDom.value) {
      chartInstance.value = echarts.init(chartDom.value);
      chartInstance.value.setOption(options);
    }
  };

  // 监听窗口大小变化，调整图表大小
  const resizeChart = () => {
    if (chartInstance.value) {
      chartInstance.value.resize();
    }
  };

  // 添加窗口大小变化监听
  const addResizeListener = () => {
    window.addEventListener("resize", resizeChart);
  };

  // 移除窗口大小变化监听
  const removeResizeListener = () => {
    window.removeEventListener("resize", resizeChart);
  };

  // 组件挂载时初始化图表并添加监听
  onMounted(() => {
    initChart();
    addResizeListener();
  });

  // 组件卸载时移除监听
  onUnmounted(() => {
    removeResizeListener();
    if (chartInstance.value) {
      chartInstance.value.dispose();
    }
  });

  return {
    initChart,
    resizeChart
  };
}
